/*
 * AutoreleasePool.cpp
 *
 *  Created on: 2013-6-23
 *  Author: xnan
 */

#include <algorithm>
#include "AutoreleasePool.h"

NS_XNL_BEGIN

AutoreleasePool * AutoreleasePool::m_instance = NULL;

AutoreleasePool::AutoreleasePool()
{
}

AutoreleasePool::~AutoreleasePool()
{
    std::list<Object*>::iterator iter = m_pool.begin();
    while( iter != m_pool.end() )
    {
        XN_RELEASE( *iter );
        iter++;
    }
    m_pool.clear();
}

void AutoreleasePool::addObject( Object * p_object )
{
    m_pool.push_back( p_object );
    XN_RETAIN( p_object );
}

void AutoreleasePool::removeObject( Object * p_object )
{
    m_pool.erase( std::find( m_pool.begin(), m_pool.end(), p_object ) );
    p_object->m_isAutorelease = false;
    if( p_object->m_refcnt <= 1 ) std::runtime_error( XN_RUNTIME_ERR_STR( "auto-release-pool remove object, reference count less than or equal to '1'" ) );
    else XN_RELEASE( p_object );
}

void AutoreleasePool::runClear()
{
    std::list<Object*>::iterator iter = m_pool.begin();
    while( iter != m_pool.end() )
    {
        if( (*iter)->m_refcnt <= 1 )
        {
            XN_RELEASE( *iter );
            iter = m_pool.erase( iter );
        }
        iter++;
    }
}

AutoreleasePool * AutoreleasePool::instance()
{
    if( AutoreleasePool::m_instance == NULL ) {
        AutoreleasePool::m_instance = new AutoreleasePool();
    }
    return AutoreleasePool::m_instance;
}

NS_XNL_END
